import Cookies from 'js-cookie';
import NetConfig from '@/config/net';

const { storage, tokenKey } = NetConfig;

export const getStorage = (key: string, type?: 'string') => {
  const data = localStorage.getItem(key);
  if (!data) return null;
  if (type === 'string') return data;
  return JSON.parse(data);
};

export const setStorage = (key: string, data: object | string) => {
  if (typeof data === 'object') {
    return localStorage.setItem(key, JSON.stringify(data));
  }
  return localStorage.setItem(key, data);
};

export const removeStorage = (key: string) => {
  localStorage.removeItem(key);
};

/**
 * @description 获取token
 */
export function getToken() {
  if (storage) {
    if (storage === 'localStorage') {
      return localStorage.getItem(tokenKey);
    }
    if (storage === 'sessionStorage') {
      return sessionStorage.getItem(tokenKey);
    }
    if (storage === 'cookie') {
      return Cookies.get(tokenKey);
    }
    return localStorage.getItem(tokenKey);
  }
  return localStorage.getItem(tokenKey);
}

/**
 * @description 存储token
 * @param token
 */
export function setToken(token: string) {
  if (storage) {
    if (storage === 'localStorage') {
      return localStorage.setItem(tokenKey, token);
    }
    if (storage === 'sessionStorage') {
      return sessionStorage.setItem(tokenKey, token);
    }
    if (storage === 'cookie') {
      return Cookies.set(tokenKey, token);
    }
    return localStorage.setItem(tokenKey, token);
  }
  return localStorage.setItem(tokenKey, token);
}

/**
 * @description 移除token
 */
export function removeToken() {
  if (storage) {
    if (storage === 'localStorage') {
      return localStorage.removeItem(tokenKey);
    }
    if (storage === 'sessionStorage') {
      return sessionStorage.clear();
    }
    if (storage === 'cookie') {
      return Cookies.remove(tokenKey);
    }
    return localStorage.removeItem(tokenKey);
  }
  return localStorage.removeItem(tokenKey);
}
